import "./App.css";
import {useState, useEffect} from 'react';
import {Button, Modal, message, Card} from 'antd';
import {PlusOutlined} from '@ant-design/icons';
import {studentsService} from "./services/StudentsService";
import {StudentTable} from "./components/StudentTable.tsx";
import {Student, StudentFormData} from "./services/types";
import {StudentForm} from "./components/StudentForm.tsx";
import {ExportButton} from "./components/ExportButton.tsx";


function App() {
    const [students, setStudents] = useState<Student[]>([]);
    const [loading, setLoading] = useState(false);
    const [modalVisible, setModalVisible] = useState(false);
    const [currentStudent, setCurrentStudent] = useState<Student>();
    const [formData, setFormData] = useState<StudentFormData>({
        name: '',
        student_id: '',
        birthday: '',
        class: ''
    });

    const loadStudents = async () => {
        setLoading(true);
        try {
            const result = await studentsService.getAllStudents();
            setStudents(result);
        } catch (error) {
            message.error(error.message);
        } finally {
            setLoading(false);
        }
    }
    useEffect(() => {
        loadStudents();

    }, []);

    const handleCreate = () => {
        setCurrentStudent(null)
        setFormData({name: '', student_id: '', birthday: '', class: ''})
        setModalVisible(true)
    }

    const handleEdit = (student: Student) => {
        setCurrentStudent(student)
        setFormData({
            name: student.name,
            birthday: student.birthday,
            class: student.class,
            student_id: student.student_id
        })
        setModalVisible(true)
    }

    const handleDelete = (id: number) => {
        Modal.confirm({
            title: '确定删除',
            content: '确定要删除此学生吗',
            async onOk() {
                try {
                    const success = await studentsService.deleteStudent(id)
                    console.log("APP success:", success)
                    if (success) {
                        message.success("删除成功")
                        await loadStudents()
                    }
                } catch (err) {
                    message.error(err.message);
                }
            }
        })
    }

    const handleSubmit = async () => {
        try {
            setLoading(true);
            if (currentStudent) {
                console.log("updataing")
                const success = await studentsService.updateStudent({...currentStudent, ...formData})
                //
                if (success) {
                    message.success("更新成功")
                    await loadStudents()
                    setModalVisible(false)
                }
            } else {
                const id = await studentsService.createStudent(formData);
                if (id) {
                    message.success("添加成功")
                    await loadStudents()
                    setModalVisible(false)
                }
            }
        } catch (error) {
            message.error(error.message);
        } finally {
            setLoading(false);
        }
    }
    return (
        <>
        <Card
            title="学生管理"
            extra={
                <div style={{display:"flex",justifyContent:"center",alignItems:'center',gap:'8px'}}>
                    <Button
                        type="primary"
                        icon={<PlusOutlined/>}
                        onClick={handleCreate}
                    >
                        添加学生
                    </Button>

                    <ExportButton data={students}></ExportButton>
                </div>
        }
        >
        <StudentTable
            data={students}
            loading={loading}
            onEdit={handleEdit}
            onDelete={handleDelete}
        />
        </Card>
    <Modal
        title={currentStudent ? '编辑学生' : '添加学生'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        confirmLoading={loading}
        width={600}>
        <StudentForm fromData={formData} onChange={(values) => setFormData(values)}></StudentForm>
    </Modal>
</>
)
    ;
}

export default App;
